package cn.yunhe.util;

import cn.yunhe.model.Brand;
import cn.yunhe.model.Cell;
import cn.yunhe.model.Layer;
import cn.yunhe.model.Map;

import java.awt.*;
import java.util.Random;

public class MapUtil {
    static Random random = new Random();
    
    public static Map buildMap(int floorHeight) {
        Map map = new Map();
        map.setFloorHeight(floorHeight);
        Layer layer1 = LayerUtil.buildLayer(floorHeight, floorHeight);
        Layer layer2 = LayerUtil.buildLayer(floorHeight, floorHeight);
        Layer layer3 = LayerUtil.buildLayer(floorHeight, floorHeight);
        
//        //将图层所有牌混乱
//        for (int i = 0; i < layer1.getCells().length * floorHeight / 3; i++) {
//            Cell[][] cells1 = layer1.getCells();
//            Cell[][] cells2 = layer2.getCells();
//            Cell[][] cells3 = layer3.getCells();
//            int cellsIndex = random.nextInt(floorHeight * floorHeight);
//            Cell cell;
//            cell = cells1[cellsIndex / floorHeight][cellsIndex % floorHeight];
//            cells1[cellsIndex / floorHeight][cellsIndex % floorHeight] = cells2[cellsIndex / floorHeight][cellsIndex % floorHeight];
//            cells2[cellsIndex / floorHeight][cellsIndex % floorHeight] = cells3[cellsIndex / floorHeight][cellsIndex % floorHeight];
//            cells3[cellsIndex / floorHeight][cellsIndex % floorHeight] = cell;
//        }
        //构建图层的链式关系
        layer3.setParent(layer2);
        layer2.setParent(layer1);
        //parent==null说明当前这⼀层已经是顶层，
        //这是循环或者递归结束的重要条件
        layer1.setParent(null);

        map.getList().add(layer1);
        map.getList().add(layer2);
        map.getList().add(layer3);
        return map;
    }
    /**
     * 函数的作⽤：判断当前牌和某⼀图层内所有牌是否有矩阵交集。
     * true 有交集，当前牌显示灰⾊牌
     * false ⽆交集，当前牌显示正常牌
     */
    public static boolean compare(Brand brand, Layer layer){
        Cell[][] cells = layer.getCells();
        for (int row = 0; row < cells.length; row++) {
            for (int col = 0; col < cells[row].length; col++) {
                //如果当前的单元格是空的，不⽤⽐较
                Cell cell = cells[row][col];
                if (cell.getState() == 1) {
                    //单元格有牌，可以⽐较
                    Rectangle temp = cell.getBrand().getBounds();
                    Rectangle rect = brand.getBounds();
                    boolean result = rect.intersects(temp);
                    if (result) {
                    //有交集，说明上层的牌被盖住了,判定结束，所以使⽤return
                        return result;
                    }
                }
            }
        }
        //此时我们需要和更上层的牌进⾏⽐较判定，
        //假如当前有9层，正在⽐较6层当中的某个牌，⽐较5层
        if (layer.getParent() != null){
            return compare(brand,layer.getParent());
        } else {
        //如果parent == null 说明已经到最顶层啦
            return false;//显示正常牌
        }
    }
}